//
//  ViewController.m
//  document
//
//  Created by C C on 2018/11/15.
//  Copyright © 2018年 C C. All rights reserved.
//

#import "ViewController.h"
#import "DocumentTableViewCell.h"
#import "DocumentModel.h"

static NSString * CELL = @"DocumentTableViewCell";

@interface ViewController ()<UITableViewDelegate, UITableViewDataSource, UIDocumentInteractionControllerDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSMutableArray <DocumentModel *>*lists;//文件数组
@property (nonatomic, copy) NSString *path;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.lists = [[NSMutableArray alloc]init];
    if (self.path == nil) {
        self.path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
        NSLog(@"文件夹地址：%@",self.path);
    }
    //遍历文件，赋值tableviewData
    [self showFiles];
    UIBarButtonItem * item = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(_add)];
    self.navigationItem.rightBarButtonItem = item;
    self.tableView.tableFooterView = [UIView new];
//    [self.tableView registerNib:[UINib nibWithNibName:CELL bundle:nil] forCellReuseIdentifier:CELL];
    [self createXLSFile];
}

//遍历文件，赋值tableviewData
- (void)showFiles{
    [self.lists removeAllObjects];
    // 1.判断文件还是目录
    NSFileManager * fileManger = [NSFileManager defaultManager];
    BOOL isDir = NO;
    BOOL isExist = [fileManger fileExistsAtPath:self.path isDirectory:&isDir];
    if (isExist) {
        // 2. 判断是不是目录
        if (isDir) {
            NSArray * dirArray = [fileManger contentsOfDirectoryAtPath:self.path error:nil];
            NSString * subPath = nil;
            for (NSString * str in dirArray) {
                subPath = [self.path stringByAppendingPathComponent:str];
                BOOL issubDir = NO;
                [fileManger fileExistsAtPath:subPath isDirectory:&issubDir];
                if (issubDir) {
                    [self.lists addObject:[[DocumentModel alloc] initWithType:FOLDER title:str]];
                } else {
                    [self.lists addObject:[[DocumentModel alloc] initWithType:JSONDATA title:str]];
                }
            }
            [self.tableView reloadData];
        } else {
            NSString *fileName = [[self.path componentsSeparatedByString:@"/"] lastObject];
            if ([fileName hasSuffix:@".m"]) {
                //do anything you want
            }
        }
    } else {
        [self showpopMessage:@"你打印的是目录或者不存在"];
    }
}


#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.lists.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        cell.imageView.contentMode = UIViewContentModeScaleAspectFit;
    }
    NSString *str = self.lists[indexPath.row].type == FOLDER ? @"document" : @"text";
    cell.imageView.image =  [UIImage imageNamed:str];
    cell.textLabel.text = self.lists[indexPath.row].title;
    return cell;
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.lists[indexPath.row].type == FOLDER) {
        UIStoryboard *main = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        ViewController *vc = [main instantiateViewControllerWithIdentifier:@"viewcontroller"];
        vc.path = [self.path stringByAppendingPathComponent:self.lists[indexPath.row].title];
        [self.navigationController pushViewController:vc animated:YES];
    } else {
//        NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"提交订单.docx"];
        NSString *path = [self.path stringByAppendingPathComponent:self.lists[indexPath.row].title];
        UIDocumentInteractionController *vc = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:path]];
        vc.delegate = self;
        NSLog(@"打开：%d", [vc presentPreviewAnimated:YES]);
    }
}

#pragma mark - UIDocumentInteractionControllerDelegate
//预览：文档交互控制器为预览视图控制器
- (UIViewController*)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController*)controller
{
    return self;
}
//视图预览文档交互控制器
- (UIView*)documentInteractionControllerViewForPreview:(UIDocumentInteractionController*)controller
{
    return self.view;
}
//预览文档交互控制器矩形
- (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController*)controller
{
    return self.view.frame;
}
//点击预览窗口的“Done”(完成)按钮时调用
- (void)documentInteractionControllerDidEndPreview:(UIDocumentInteractionController*)_controller
{
    
}



- (void)_add {
    __weak typeof(self) weakself = self;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"新建类型" message:@"选择新建文件夹还是数据文件" preferredStyle:UIAlertControllerStyleActionSheet];
    [alert addAction:[UIAlertAction actionWithTitle:@"文件夹" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIAlertController *folderAlert = [UIAlertController alertControllerWithTitle:@"输入文件夹名字" message:nil preferredStyle:UIAlertControllerStyleAlert];
        [folderAlert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
            
        }];
        [folderAlert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        }]];
        [folderAlert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [weakself addFolderWithTitle:folderAlert.textFields.firstObject.text];
        }]];
        [weakself presentViewController:folderAlert animated:YES completion:nil];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"数据文件" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIAlertController *jsonAlert = [UIAlertController alertControllerWithTitle:@"输入文件名" message:nil preferredStyle:UIAlertControllerStyleAlert];
        [jsonAlert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
            
        }];
        [jsonAlert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        }]];
        [jsonAlert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [weakself addJsonWithTitle:jsonAlert.textFields.firstObject.text];
        }]];
        [weakself presentViewController:jsonAlert animated:YES completion:nil];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [action setValue:[UIColor redColor] forKey:@"titleTextColor"];
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)addJsonWithTitle:(NSString *)title {
    if ([self hasSameTitleForDocumenType:JSONDATA title:title]) {
        [self showpopMessage:@"重名了"];
        return;
    }
    NSDictionary *dict = @{@"name" : @"me",
                           @"do" : @"something",
                           @"with" : @"her",
                           @"address" : @"home"};
    
    BOOL canjson = [NSJSONSerialization isValidJSONObject:dict];
    if (canjson) {
        NSData * jsondata = [NSJSONSerialization dataWithJSONObject:dict options:0 error:NULL];
        NSString *savePath = [self.path stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.json",title]];
        if ([jsondata writeToFile:savePath atomically:YES]) {
            [self showFiles];
        } else {
            [self showpopMessage:@"存入失败"];
        }
    }
}

- (void)addFolderWithTitle:(NSString *)title {
    if ([self hasSameTitleForDocumenType:FOLDER title:title]) {
        [self showpopMessage:@"重名了"];
        return;
    }
    NSString * path = [self.path stringByAppendingPathComponent:title];
    NSFileManager *manager = [NSFileManager defaultManager];
    NSError *err = [[NSError alloc]init];
    if ([manager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&err]) {
        [self showFiles];
    } else {
        [self showpopMessage:err.localizedDescription];
    }
    
}

- (BOOL)hasSameTitleForDocumenType:(DOCUMENTTYPE)documentType title:(NSString *)title{
    NSMutableArray <NSString *> *folderArr = [[NSMutableArray alloc]init];
    NSMutableArray <NSString *> *jsonArr = [[NSMutableArray alloc]init];
    NSFileManager * fileManger = [NSFileManager defaultManager];
    BOOL isDir = NO;
    BOOL isExist = [fileManger fileExistsAtPath:self.path isDirectory:&isDir];
    if (isExist) {
        NSArray * dirArray = [fileManger contentsOfDirectoryAtPath:self.path error:nil];
        NSString * subPath = nil;
        for (NSString * str in dirArray) {
            subPath = [self.path stringByAppendingPathComponent:str];
            BOOL issubDir = NO;
            [fileManger fileExistsAtPath:subPath isDirectory:&issubDir];
            if (issubDir) {
                [folderArr addObject:str];
            } else {
                [jsonArr addObject:str];
            }
        }
    } else {
        [self showpopMessage:@"你打印的是目录或者不存在"];
        return YES;
    }
    switch (documentType) {
        case FOLDER: {
            for (NSString * name in folderArr) {
                if ([name isEqualToString:title]) {
                    return YES;
                }
            }
            return NO;
        }
            break;
        case JSONDATA: {
            for (NSString * name in jsonArr) {
                if ([name isEqualToString:title]) {
                    return YES;
                }
            }
            return NO;
        }
            break;
        default:
            return NO;
            break;
    }
    return NO;
}

- (void)showpopMessage:(NSString *)message {
    UIAlertController *vc = [UIAlertController alertControllerWithTitle:message message:nil preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:vc animated:YES completion:nil];
}


#pragma mark - 创建excel
- (void)createXLSFile {
    // 创建存放XLS文件数据的数组
    NSMutableArray  *xlsDataMuArr = [[NSMutableArray alloc] init];
    // 第一行内容
    [xlsDataMuArr addObject:@"Time"];
    [xlsDataMuArr addObject:@"Address"];
    [xlsDataMuArr addObject:@"Person"];
    [xlsDataMuArr addObject:@"Reason"];
    [xlsDataMuArr addObject:@"Process"];
    [xlsDataMuArr addObject:@"Result"];
    // 100行数据
    for (int i = 0; i < 100; i ++) {
        [xlsDataMuArr addObject:@"2016-12-06 17:18:40"];
        [xlsDataMuArr addObject:@"GuangZhou"];
        [xlsDataMuArr addObject:@"Mr.Liu"];
        [xlsDataMuArr addObject:@"Buy"];
        [xlsDataMuArr addObject:@"TaoBao"];
        [xlsDataMuArr addObject:@"Debt"];
    }
    // 把数组拼接成字符串，连接符是 \t（功能同键盘上的tab键）
    NSString *fileContent = [xlsDataMuArr componentsJoinedByString:@"\t"];
    // 字符串转换为可变字符串，方便改变某些字符
    NSMutableString *muStr = [fileContent mutableCopy];
    // 新建一个可变数组，存储每行最后一个\t的下标（以便改为\n）
    NSMutableArray *subMuArr = [NSMutableArray array];
    for (int i = 0; i < muStr.length; i ++) {
        NSRange range = [muStr rangeOfString:@"\t" options:NSBackwardsSearch range:NSMakeRange(i, 1)];
        if (range.length == 1) {
            [subMuArr addObject:@(range.location)];
        }
    }
    // 替换末尾\t
    for (NSUInteger i = 0; i < subMuArr.count; i ++) {
#warning  下面的6是列数，根据需求修改
        if ( i > 0 && (i%6 == 0) ) {
            [muStr replaceCharactersInRange:NSMakeRange([[subMuArr objectAtIndex:i-1] intValue], 1) withString:@"\n"];
        }
    }
    // 文件管理器
    NSFileManager *fileManager = [[NSFileManager alloc]init];
    //使用UTF16才能显示汉字；如果显示为#######是因为格子宽度不够，拉开即可
    NSData *fileData = [muStr dataUsingEncoding:NSUTF16StringEncoding];
    // 文件路径
    NSString *path = NSHomeDirectory();
    NSString *filePath = [path stringByAppendingPathComponent:@"/Documents/export.xls"];
    NSLog(@"文件路径：\n%@",filePath);
    // 生成xls文件
    [fileManager createFileAtPath:filePath contents:fileData attributes:nil];
}

@end
